// AIChatCard.kt
package com.example.nutritionmanager

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.nutritionmanager.ai.Message
import com.example.nutritionmanager.bodys.requestBodys.RecordItem
import com.example.nutritionmanager.conversationApi.SSEClient
import kotlinx.coroutines.launch

/**
 * 代表一条消息的简单数据类
 */
//data class Message(var text: String, val isUser: Boolean)

/**
 * 负责显示 AI 对话的卡片组件
 */
@Composable
fun AIChatCard(
    modifier: Modifier = Modifier,
    defaultText: String = "用户性别男，年龄20岁，身高180cm，体重80kg，减脂期。今日已摄入：碳水100g，蛋白20g，脂肪20g，k：30mg。当前摄入食物：碳水10g，脂肪30g，蛋白质0g",
    // 新增外部触发参数
    externalMessage: String? = null,
    onExternalMessageProcessed: () -> Unit = {}
) {
    val colorScheme = MaterialTheme.colorScheme
    // AI 对话状态
    var userMessage by remember { mutableStateOf("") }
    var messages by remember { mutableStateOf(listOf<Message>()) }
    var isEditing by remember { mutableStateOf(false) } // 标记是否开始编辑输入框
    val sseClient = remember { SSEClient() }
    val scope = rememberCoroutineScope()

    // 状态保持 LazyListState，用于控制滚动
    val listState = rememberLazyListState()

    // 监听外部消息变化
    LaunchedEffect(externalMessage) {
        externalMessage?.let { msg ->
            if (msg.isNotBlank()) {
                // 添加系统消息
                messages = messages + Message(text = msg, isUser = true)
                messages = messages + Message(text = "", isUser = false) // 初始化 AI 消息
                // 发起SSE请求
                sseClient.startSSERequest(msg, object : SSEClient.MessageListener {
                    override fun onAppendMessage(text: String) {
                        // 更新最后一条AI消息
                        messages = messages.toMutableList().apply {
                            val lastIndex = lastIndex
                            if (lastIndex >= 0) {
                                this[lastIndex] = this[lastIndex].copy(text = this[lastIndex].text + text)
                            }
                        }
                    }

                    override fun onFinish() {
                        onExternalMessageProcessed()
                    }
                })
            }
        }
    }

    // 自动滚动到底部，当新消息添加时
    LaunchedEffect(messages.size) {
        if (messages.isNotEmpty()) {
            listState.animateScrollToItem(messages.size - 1)
        }
    }

    Card(
        modifier = modifier
            .fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = colorScheme.surface),
        shape = MaterialTheme.shapes.medium
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp) // 内边距
        ) {
            // 显示聊天记录
            LazyColumn(
                modifier = Modifier
                    .heightIn(max = 500.dp, min = 150.dp) // 设置最大高度，根据需要调整
                    .fillMaxWidth(),
                state = listState
            ) {
                items(messages) { message ->
                    MessageBubble(message = message)
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 输入框和发送按钮
            Row(
                modifier = Modifier
                    .height(64.dp)
                    .fillMaxWidth()
                    .border(width = 1.dp, color = Color.Gray)
                    .padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                BasicTextField(
                    value = userMessage,
                    onValueChange = {
                        userMessage = it
                        isEditing = it.isNotEmpty() // 当用户输入时，标记为正在编辑
                    },
                    textStyle = TextStyle(fontSize = 16.sp, color = colorScheme.onSurface),
                    modifier = Modifier
                        .weight(1f)
                        .background(colorScheme.surfaceVariant, RoundedCornerShape(8.dp))
                        .padding(12.dp)
                        .fillMaxHeight()
                        .heightIn(min = 56.dp, max = 200.dp) // 动态调整高度
                        .wrapContentHeight(Alignment.CenterVertically)
                )
                Spacer(modifier = Modifier.width(8.dp))
                IconButton(onClick = {
                    // 发送用户消息或默认内容
                    val messageToSend = if (userMessage.isEmpty()) defaultText else userMessage
                    if (messageToSend.isNotBlank()) {
                        messages = messages + Message(text = messageToSend, isUser = true)
                        messages = messages + Message(text = "", isUser = false) // 初始化 AI 消息

                        // 发起 SSE 请求
                        sseClient.startSSERequest(messageToSend, object : SSEClient.MessageListener {
                            override fun onAppendMessage(text: String) {
                                // 动态更新最后一条消息
                                messages = messages.toMutableList().apply {
                                    val lastIndex = this.size - 1
                                    if (lastIndex >= 0) {
                                        this[lastIndex] = this[lastIndex].copy(text = this[lastIndex].text + text)
                                    }
                                }
                            }

                            override fun onFinish() {
                                // 完成时可以进行其他操作，如提示用户
                            }
                        })

                        userMessage = "" // 发送后清空输入框
                    }
                }) {
                    Icon(Icons.Filled.Send, contentDescription = "发送", tint = colorScheme.onSurface)
                }
            }
        }
    }
}

/**
 * 消息气泡组件
 */
@Composable
fun MessageBubble(message: Message) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = if (message.isUser) Arrangement.End else Arrangement.Start
    ) {
        Box(
            modifier = Modifier
                .padding(8.dp)
                .background(
                    color = if (message.isUser) MaterialTheme.colorScheme.primary else Color.LightGray,
                    shape = RoundedCornerShape(12.dp)
//                    shape = MaterialTheme.shapes.medium

                )
                .padding(12.dp)
        ) {
            Text(
                text = message.text,
                style = TextStyle(color = if (message.isUser) Color.White else Color.Black)
            )
        }
    }
}
